<template>
  <el-dialog
    title="添加地区"
    :visible.sync="AddMapDialog"
    @opened="handleOpened"
    @closed="handleClose"
    :lock-scroll="false"
    close-on-press-escape
    v-dialogDrag
    :close-on-click-modal="false"
  >
    <el-tabs
      class="tabHight"
      :tab-position="tabPosition"
      v-model="mapTabs"
      @tab-click="invalidateMap"
    >
      <el-tab-pane label="详情" name="first">
        <div class="">
          <el-form
            :model="mapForm"
            :rules="rules"
            ref="mapForm"
            label-width="13%"
            size="mini"
          >
            <el-form-item label="Token:" prop="token">
              <el-input v-model="mapForm.token" style="width: 100%"></el-input>
            </el-form-item>
            <el-form-item label="名称:" prop="name">
              <el-input v-model="mapForm.name" style="width: 100%"></el-input>
            </el-form-item>
          </el-form>
          <!-- 地图 -->
          <div v-if="AddMapShow">
            <div id="addMapSite" v-init-screen-h="180"></div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="元数据" name="second">
        <metaData
          :editmetaData="editmetaData"
          :isedit="isedit"
          @sendmetaDatas="sendmetaData"
          ref="clear"
        />
      </el-tab-pane>
    </el-tabs>
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="cancel">取 消</el-button>
      <el-button
        size="mini"
        type="primary"
        @click="subMapForm('mapForm')"
        :loading="btnLoading"
        >确 定
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  initMap,
  addControlOptions,
  createIcon,
} from "../../utils/leaflet-map";
import MetaData from "../opensite/metaData.vue";
import { TOKEN_RULES } from "@/utils/local";
import { postZones } from "@/api/zones";
export default {
  components: {
    MetaData,
  },
  props: {
    AddMapShow: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      btnLoading: false,
      isedit: false,
      metaDataJson: {},
      editmetaData: {},
      mapTabs: "first",
      map: {},
      layer: [],
      mapBounds: [],
      tabPosition: "left",
      AddMapDialog: false,
      mapForm: {
        token: "",
        name: "",
        bounds: {},
      },
      rules: {
        token: TOKEN_RULES,
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          {
            min: 1,
            max: 15,
            message: "长度在 1 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
      areaToken: this.$route.query.areaToken,
      formInline: { date: "", name: "" },
    };
  },
  watch: {
    AddMapShow(newVal, oldVal) {
      // this.map = {};
      this.AddMapDialog = newVal;
      // this.load_Map_2();
      console.log(
        newVal,
        this.AddMapDialog,
        "AddMapDialogAddMapDialogAddMapDialogAddMapDialog"
      );
    },
  },
  mounted() {
    // this.$nextTick(() => {
    //   this.load_Map_2();
    // });
  },
  methods: {
    handleOpened() {
      this.load_Map_2();
    },
    cancel() {
      this.handleClose();
    },
    handleClose() {
      this.$emit("changeShow", "false");
      this.mapForm = {
        token: "",
        name: "",
      };
      this.$refs.clear.clearMeteDada();
      this.layer = [];
      if (this.map) {
        this.map.remove();
      }
      this.map = "";
    },
    // 初始化地图
    load_Map_2() {
      var that = this;
      var latlng = that.mapForm.bounds;
      var map = initMap("addMapSite", latlng, 5);
      const options = [
        "drawRectangle",
        "drawPolygon",
        "removalMode",
        "enable",
        "editMode",
      ];
      map.pm.addControls({
        position: "topleft",
        drawPolygon: options.includes("drawPolygon"), // 添加绘制多边形
        drawMarker: options.includes("drawMarker"), //添加按钮以绘制标记
        drawCircleMarker: options.includes("drawCircleMarker"), //添加按钮以绘制圆形标记
        drawPolyline: options.includes("drawPolyline"), //添加按钮绘制线条
        drawRectangle: options.includes("drawRectangle"), //添加按钮绘制矩形
        drawCircle: options.includes("drawCircle"), //  添加按钮绘制圆圈
        editMode: options.includes("editMode"), //  添加按钮编辑多边形
        dragMode: options.includes("dragMode"), //   添加按钮拖动多边形
        cutPolygon: options.includes("cutPolygon"), // 添加一个按钮以删除图层里面的部分内容
        removalMode: options.includes("removalMode"), // 清除图层
      });

      // 设置绘制后的线条颜色等
      map.pm.setPathOptions({
        color: "orange",
        fillColor: "green",
        fillOpacity: 0.4,
      });
      map.pm.setLang("zh"); //设置语言  en, de, it, ru, ro, es, fr, pt_br, zh , nl
      // addControlOptions(map, [
      //   "drawRectangle",
      //   "drawPolygon",
      //   "removalMode",
      //   "enable",
      //   "editMode",
      // ]);

      map.on("pm:create", (e) => {
        if (that.layer) {
          map.removeLayer(that.layer); // 移除已有图层,限制只有一个marker
        }
        // 清空参数，只保留当前
        that.mapBounds = [];
        // 转换数据格式
        that.layer = e.layer;
        let maplist = e.layer._latlngs;
        let ele = {};
        maplist[0].forEach((item) => {
          ele = {
            latitude: item.lat,
            longitude: item.lng,
          };
          that.mapBounds.push(ele);
        });
      });
      map.on("pm:remove", (e) => {
        that.layer = [];
      });
      that.map = map;
    },
    // 提交
    subMapForm(mapForm) {
      this.$refs[mapForm].validate((valid) => {
        if (valid) {
          let formData = {};
          formData.areaToken = this.areaToken;
          formData.borderOpacity = 1;
          formData.fillOpacity = 1;
          formData.metadata = this.metaDataJson;
          formData.token = this.mapForm.token;
          formData.name = this.mapForm.name;
          formData.borderColor = "#000000";
          formData.fillColor = "#FF0000";
          formData.bounds = this.mapBounds;
          this.btnLoading = true;
          postZones(formData)
            .then((res) => {
              this.$msg({
                type: "success",
                message: "操作成功!",
              });
              this.$emit("gteZoneList");
              this.handleClose();
            })
            .finally((f) => {
              this.btnLoading = false;
            });
        } else {
          console.log("错误信息!");
          return false;
        }
      });
    },
    //地图重新调整位置
    invalidateMap(tab) {
      if (tab.name == "first") {
        this.$nextTick(() => {
          this.map.invalidateSize(true);
        });
      }
    },

    //元数据页回传
    sendmetaData(md) {
      this.metaDataJson = md;
    },
  },
};
</script>

<style scoped>
#addMapSite {
  width: 100%;
  height: 100%;
  z-index: 100;
  overflow: hidden !important;
}
</style>